<template>
    <view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox flex_wrap row_between">
            <u--text text="视频类型" color="#000" size="28rpx" />
            <view class="flex_wrap" @click="chooseType()">
                <view class="title">{{ typeName }}</view>
                <u-icon
                    name="arrow-right"
                    color="#777777 "
                    size="36rpx"
                ></u-icon>
            </view>
        </view>
        <u-picker
            :show="typeShow"
            ref="uPicker"
            :columns="columns"
            keyName="typeName"
            @confirm="confirm"
            @cancel="typeShow = false"
        ></u-picker>

        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox flex_wrap row_between">
            <u--text text="视频名字" color="#000" size="28rpx" />
            <view class="flex_wrap" @click="addName()">
                <view class="title">{{ videoName }}</view>
                <u-icon
                    name="arrow-right"
                    color="#777777 "
                    size="36rpx"
                ></u-icon>
            </view>
        </view>
        <u-line color="#f3f3f3" length="2rpx"></u-line>
        <view class="cellBox flex_wrap row_between">
            <u--text text="视频简介" color="#000" size="28rpx" />
            <view class="flex_wrap" @click="addInfo()">
                <view class="title">{{ videoInfo }}</view>
                <u-icon
                    name="arrow-right"
                    color="#777777 "
                    size="36rpx"
                ></u-icon>
            </view>
        </view>
        <u-line color="#f3f3f3" length="2rpx"></u-line>
        <view style="background: #fff; padding: 30rpx">
            <view class="content huaTiBox">
                <u-textarea
                    ref="isInputFocus"
                    v-model="huaTi"
                    :maxlength="1000"
                    placeholder="请输入您要关联的话题~"
                    autoHeight
                    :customStyle="{
                        backgroundColor: '#F8F8F8',
                        fontSize: '28rpx',
                        border: 'none',
                        minHeight: '120rpx',
                    }"
                ></u-textarea>
                <view class="talkBox" @click="addTalkBtn"># 话题</view>
            </view></view
        >
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox">
            <u--text
                text="上传视频"
                color="#000"
                size="28rpx"
                margin="0 0 24rpx 0"
            />
            <view>
                <u-upload
                    :maxCount="1"
                    :fileList="fileList1"
                    @delete="deleteVideo"
                    @afterRead="afterRead1"
                    accept="video"
                    width="196rpx"
                    height="196rpx"
                    compressed
                    maxDuration="30"
                ></u-upload>
            </view>
        </view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox">
            <u--text
                text="视频封面"
                color="#000"
                size="28rpx"
                margin="0 0 24rpx 0"
            />
			<view
			    class="uplondImg"
				v-if="videoPicture"
			>
			    <image class="uplondImg_img" :src="videoPicture" mode=""></image>
			    <view class="uplondImg_icon" @click="delMain(index)">
			        <u-icon
			            name="close-circle-fill"
			            color="#737374"
			            size="20"
			        ></u-icon>
			    </view>
			</view>
			<view
			    class="uplondBtn"
			    @click="tapUpdateImg"
			    v-if="!videoPicture"
			>
			    <u-icon
			        name="camera-fill"
			        color="#D3D4D6"
			        size="28"
			    ></u-icon>
			</view>
        </view>
        <view class="bottom">
            <u-button
                :loading="btnLoading"
                text="发布"
                color="#1682FF"
                :disabled="uploadLoading"
                shape="circle"
                @click="sumbit()"
            />
        </view>

        <u-modal
            :show="nameShow"
            showCancelButton
            title="视频名称"
            @confirm="nameConfirm"
            @cancel="nameShow = false"
        >
            <view style="width: 560rpx; margin: 0 auto">
                <u-textarea
                    ref="textareaName"
                    height="300rpx"
                    v-model="videoName1"
                    :customStyle="textAreaCustomStyle"
                    placeholder="请输入内容"
                    fixed
                    count
                    maxlength="100"
                ></u-textarea>
            </view>
        </u-modal>

        <u-modal
            :show="infoShow"
            showCancelButton
            title="视频简介"
            @confirm="infoConfirm"
            @cancel="infoShow = false"
        >
            <view style="width: 560rpx; margin: 0 auto">
                <u-textarea
                    ref="textarea"
                    height="300rpx"
                    v-model="videoInfo1"
                    :customStyle="textAreaCustomStyle"
                    placeholder="请输入内容"
                    fixed
                    count
                    maxlength="100"
                ></u-textarea>
            </view>
        </u-modal>
    </view>
</template>

<script>
import { baseUrl } from "@/config/tendIdConfig";
import { mapGetters } from "vuex";
import { uploadVideo } from "@/api/consultationSalesman.js";
import { uploadVideoCustomer } from "@/api/customerAgent.js";
export default {
    data() {
        return {
            btnLoading: false,
            uploadLoading: true,
            textAreaCustomStyle: {
                backgroundColor: "#EDEDED",
                color: "#666",
                width: "100%",
                padding: "20rpx",
                paddingBottom: "40rpx",
                boxSizing: "border-box",
                fontSize: "26rpx",
            },
            navbarData: {},
            typeShow: false,
            columns: [],
            typeName: "",
            typeNameId: "",
            nameShow: false,
            videoName: "",
            videoName1: "",
            infoShow: false,
            videoInfo: "",
            videoInfo1: "",
            huaTi: "",
            fileList1: [],
            releaseManId: "",
            currentTab: 0,
			videoType:'',
			videoPicture:''
        };
    },
    mounted() {
        this.handelData();
    },
    computed: {
        ...mapGetters(["userInfo"]),
    },
    onReady() {
        this.$refs.textarea.setFormatter(this.formatter);
        this.$refs.textareaName.setFormatter(this.formatterName);
    },
    onLoad(o) {
        if (o.releaseManId) this.releaseManId = o.releaseManId;
        if (o.currentTab) this.currentTab = o.currentTab;
    },
    methods: {
        addTalkBtn() {
            console.log("object :>> 111", this.huaTi);
            this.huaTi && (this.huaTi = this.huaTi + " #");
            if (!this.huaTi) this.huaTi = "#";
        },
        formatter(value) {
            if (value.length > 100) {
                return value.slice(0, 100);
            } else {
                return value;
            }
        },
        formatterName(value) {
            if (value.length > 100) {
                return value.slice(0, 100);
            } else {
                return value;
            }
        },
        sumbit() {
            if (!this.typeName.length) return uni.$u.toast("请选择视频类型！");
            if (!this.videoName.length) return uni.$u.toast("请输入视频名字！");
            if (!this.videoInfo.length) return uni.$u.toast("请输入视频简介！");
            if (!this.videoPicture || !this.fileList1.length)
                return uni.$u.toast("请上传图片/视频！");

            this.btnLoading = true;

            const params = {
                checkStatus: 0, //审核状态（0:通过 1:不通过）
                recordType: 8, //视频
                releaseStatus: 1, //发布
                releaseManId: this.userInfo.id, //发布人ID
                videoType: this.videoType, //视频类型
                videoTypeId: this.typeNameId, //视频类型id
                videoName: this.videoName, //视频名字
                videoIntro: this.videoInfo, //视频简介
                videoCover: this.videoPicture,
                videoUrl: this.fileList1[0]["url"], //视频地址
            };

            if (this.huaTi) params.tag = this.huaTi.replace(/#/g, ",");
            if (this.releaseManId) {
                params.releaseManId = this.releaseManId;
                uploadVideoCustomer(params).then((res) => {
                    uni.$u.toast("提交成功");
                    uni.$emit("currentTab", this.currentTab);
                    uni.navigateBack({
                        delta: 1,
                    });
                });
                return;
            }
            console.log(params, "参数");
            uploadVideo(params).then((res) => {
                uni.$u.toast("提交成功");
                uni.$emit("currentTab", 2);
                uni.navigateBack({
                    delta: 1,
                });
            });
        },
		
		delMain(index) {
		     this.videoPicture = ''
		},
		tapUpdateImg(){
			uni.chooseImage({
				count: 1, 
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				loop: true,
				success: res => {
					var tempFilePaths = res.tempFilePaths;
					let _this = this;
					uni.uploadFile({
					    url: `${baseUrl}/salesman/fileOss/uploadFileImg`, //这里写自己的接口
					    filePath: tempFilePaths[0],
					    header: {
					        "Content-Type": "multipart/form-data",
					        Authorization:
					            `Bearer ${uni.getStorageSync("access_token")}` || "",
					    },
					    name: "file",
					    success: (res) => {
					        const result = JSON.parse(res.data);
					        if (result.code === 200) {
					            uni.showToast({
					                title: "上传成功",
					                icon: "success",
					            });
					            _this.videoPicture = result.data;
					            console.log(_this.videoPicture, ">>");
					        } else {
					            uni.showToast({
					                title: "上传失败",
					                icon: "fail",
					            });
					        }
					    },
					});
				}
			});
		},
		
		
        addName() {
            this.videoName1 = this.videoName;
            this.nameShow = true;
        },
        nameConfirm() {
            this.nameShow = false;
            this.videoName = this.videoName1;
        },
        addInfo() {
            this.videoInfo1 = this.videoInfo;
            this.infoShow = true;
        },
        infoConfirm() {
            this.videoInfo = this.videoInfo1;
            this.infoShow = false;
        },
        //初始化开始数据
        handelData() {
            const token =
                this.$store.getters?.customer_token ||
                uni.getStorageSync("customer_token");
            const that = this;
            uni.request({
                url:
                    baseUrl +
                    "/customer/video_type_customer/open/getVideoTypeTree",
                method: "POST",
                header: {
                    Authorization: token,
                },
                data: {
                    parentId: 0,
                    typeModule: "0",
                },
                success(res) {
                    if ([991, 992, 401].includes(res.data.code)) {
                        uni.$u.toast(res.data.msg);
                        that.$store.commit("SET_LOGOUT");
                        uni.navigateTo({
                            url: "/pages/user/phone/index",
                        });
                        return;
                    }
                    const result = res.data.data[0].typeChild ?? [];
                    // that.columns = result
                    that.columns.push(result);
                    console.log(result, "result???", that.columns);
                },
            });
        },
        chooseType() {
            this.typeShow = true;
        },
        // 确认选中的数据
        confirm(e) {
			console.log(e,'eee')
            this.typeName = e.value[0].typeName;
            this.videoType = e.value[0].parentIdSet;
            this.typeNameId = e.value[0].id;
            console.log(this.videoType,'this.videoType');
            this.typeShow = false;
        },
        async afterRead1(event) {
            this.uploadLoading = true;
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList1.length;
            lists.map((item) => {
                this.fileList1.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                this.uploadLoading = false;
                let item = this.fileList1[fileListLen];
                this.fileList1.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        uploadResult: result,
                        url: result,
                    })
                );
				this.videoPicture = this.fileList1[0].uploadResult+'?x-oss-process=video/snapshot,t_1000,f_jpg'
				console.log(this.fileList1[0].uploadResult,'this.fileList1>>',this.videoPicture)
                fileListLen++;
            }
        },
        deleteVideo(event) {
            this.fileList1.splice(event.index, 1);
			this.videoPicture = ''
        },
        async uploadFilePromise(url) {
            const that = this;

            return new Promise((resolve, reject) => {
                const token = uni.getStorageSync("access_token");
                let a = uni.uploadFile({
                    url: `${baseUrl}/${this.$store.getters?.authority}/fileOss/uploadFileImg`,
                    filePath: url,
                    header: {
                        "Content-Type": "multipart/form-data",
                        Authorization: `Bearer ${token}` || "",
                    },
                    name: "file",
                    success: (res) => {
                        const result = JSON.parse(res.data);
                        if (result.code === 200) {
                            uni.showToast({
                                title: "上传成功",
                                icon: "success",
                            });
                            setTimeout(() => {
                                resolve(result.data);
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "fail",
                            });
                            setTimeout(() => {
                                reject(result.msg);
                            }, 1000);
                        }
                    },
                });
            });
        },
    },
};
</script>
<style lang="scss" scoped>
page {
    background: #f5f5f5;
    color: #333333;
}

.cellBox {
    background-color: #ffffff;
    padding: 34rpx 28rpx;
    /* line-height: 112rpx; */
    font-size: 32rpx;
    color: #3d3d3d;
}

.title {
    overflow: hidden;
    width: 500rpx;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: end;
}
.bottom {
    width: 100%;
    padding: 10rpx 40rpx 60rpx;
    box-sizing: border-box;
}
.huaTiBox {
    ::v-deep .u-textarea__field {
        color: #588bf3 !important;
    }
}
.content {
    background: #f8f8f8;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding-bottom: 20rpx;
}
.talkBox {
    width: 112rpx;
    height: 40rpx;
    background: #588bf3;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    line-height: 40rpx;
    text-align: center;
    color: #fff;
    font-weight: 400;
    font-size: 28rpx;
    margin: 0 0 16rpx 60rpx;
}
.uplondBtn {
    width: 198rpx;
    height: 198rpx;
    background-color: #f4f5f7;
    display: flex;
    justify-content: center;
    align-items: center;
}
.uplondImg {
    width: 198rpx;
    height: 198rpx;
    background-color: #f4f5f7;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    position: relative;
    &_img {
        width: 198rpx;
        height: 198rpx;
    }
    &_icon {
        position: absolute;
        top: 0;
        right: 0;
    }
}
</style>
